package com.its.web;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.its.pojo.BusInsurancePolicy;
import com.its.pojo.BusSurveyInfo;
import com.its.pojo.HupCompany;
import com.its.service.BusSurveyInfoService;
import com.its.util.HttpStatusEnum;
import com.its.util.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 朱厚强
 * @since 2024年01月04日
 */
@RestController
@RequestMapping("/busSurveyInfo")
@Api(tags = "查勘-api")
@Slf4j
public class BusSurveyInfoController {
    @Autowired
    private BusSurveyInfoService busSurveyInfoService;
    /**
     * 查询所有的查勘信息
     */
    @GetMapping("/pageList")
    public Result queryAll(
            @RequestParam (value = "pageNum", required = false,defaultValue = "1") int pageNum,
            @RequestParam (value = "pageSize", required = false ,defaultValue = "5") int pageSize,
            @RequestParam (value = "claimReportId", required = false)   String claimReportId){
        PageInfo<BusSurveyInfo> pageInfo = busSurveyInfoService.queryAll(pageNum,pageSize,claimReportId);
        if (pageInfo.getSize()>0){
            return Result.ok().code(HttpStatusEnum.SUCCESS.getCode()).data(pageInfo).message("查询成功");
        }else {
            return Result.ok().code(HttpStatusEnum.ERROR.getCode()).data(pageInfo).message("查询失败");
        }
    }
    /**
     * 查询我的调度信息集合
     */
    @GetMapping("/queryForDispatchList")
    public Result queryForDispatchList(){
        return busSurveyInfoService.queryForDispatchListS();
    }
    /**
     * 根据查询到的调度信息去查询保单以及报案信息
     */
    @GetMapping("/queryClaimAndPolicy/{dispatchId}")
    public Result queryClaimAndPolicy(@PathVariable Integer dispatchId){
        return busSurveyInfoService.queryClaimAndPolicy(dispatchId);
    }
    /**
     * 删除信息(逻辑删除)
     * @return
     */
    @DeleteMapping("/remove")
    public Result remove(@RequestParam Integer id ){
        boolean b = busSurveyInfoService.updateById(new BusSurveyInfo().setId(Long.valueOf(id)).setExist(1));
        if (b){
            return Result.ok().code(HttpStatusEnum.SUCCESS.getCode()).message("删除成功");
        }else {
            return Result.error().code(HttpStatusEnum.ERROR.getCode()).message("删除失败");
        }
    }
    /**
     * 添加数据
     */
    @PostMapping("/add")
    public Result add(@RequestBody BusSurveyInfo busSurveyInfo){
        boolean b = busSurveyInfoService.surveySave(busSurveyInfo);
        if (b){
            return Result.ok().code(HttpStatusEnum.SUCCESS.getCode()).message("添加查勘信息成功");
        }else {
            return Result.error().code(HttpStatusEnum.ERROR.getCode()).message("添加查勘信息失败");
        }
    }
    /**
     * 根据id获取信息
     * @return
     */
    @GetMapping("/getById/{id}")
    public Result getById(@PathVariable String id){
        BusSurveyInfo busSurveyInfo = busSurveyInfoService.getById(id);
        if (busSurveyInfo != null){
            return Result.ok().data(busSurveyInfo).code(HttpStatusEnum.SUCCESS.getCode()).message("查询成功");
        }else {
            return Result.error().data(busSurveyInfo).code(HttpStatusEnum.ERROR.getCode()).message("查询失败");
        }
    }
    /**
     * 更新数据
     */
    @PutMapping("/update")
    public Result update(@RequestBody BusSurveyInfo busSurveyInfo){
        boolean b = busSurveyInfoService.updateById(busSurveyInfo);
        if (b){
            return Result.ok().code(HttpStatusEnum.SUCCESS.getCode()).message("修改公司信息成功");
        }else {
            return Result.error().code(HttpStatusEnum.ERROR.getCode()).message("修改公司信息失败");
        }
    }
    /**
     * default导出
     */
    @GetMapping("/surveyExport")
    public Result surveyExport(@RequestParam("id") Integer id) {
        try {
            // 根据传入的ID查询指定记录
            BusSurveyInfo surveyInfo = busSurveyInfoService.getById(id);

            if (surveyInfo == null) {
                return Result.error().message("未找到指定记录");
            }

            // 定义导出内容，将查询到的记录添加到列表中
            List<BusSurveyInfo> list = new ArrayList<>();
            list.add(surveyInfo);

            // 导出Excel
            Workbook excel = ExcelExportUtil.exportExcel(new ExportParams("查勘报告", "查勘报告"), BusSurveyInfo.class, list);
            // 指定当前导出的数据到目标位置
            FileOutputStream fos = new FileOutputStream(new File("D:/查勘报告.xlsx"));
            excel.write(fos);
            fos.close();
            return Result.ok().message("导出成功");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error().message("导出失败");
        }
    }
    /**
     * 游览器导出 <br>
     * 这里只能用void返回，不然会下载不了。
     */
    @GetMapping("/surveyExportExc/{id}")
    public void surveyExportL(@PathVariable("id") Integer id, HttpServletResponse response) throws IOException {
        try {
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 设置防止中文名乱码
            String filename = URLEncoder.encode("查勘报告", "utf-8");

            // 文件下载方式(附件下载还是在当前浏览器打开)
            response.setHeader("Content-disposition", "attachment;filename=" + filename + ".xlsx");

            // 根据传入的ID查询指定记录
            BusSurveyInfo surveyInfo = busSurveyInfoService.getById(id);

            if (surveyInfo == null) {
                System.out.println("未找到指定记录");
            }

            // 定义导出内容，将查询到的记录添加到列表中
            List<BusSurveyInfo> list = new ArrayList<>();
            list.add(surveyInfo);
            // 导出Excel
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("查勘报告", "查勘报告"), BusSurveyInfo.class, list);

            // 导出流信息到浏览器
            workbook.write(response.getOutputStream());

            // 释放资源
            workbook.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //easypoi导出word
    @GetMapping("/surveyExportWord/{id}")
    public void exportWord( @PathVariable("id") Integer id, HttpServletResponse response) throws Exception {
        // 获取模板文档
        File rootFile = new File(ResourceUtils.getURL("classpath:").getPath());
        File templateFile = new File(rootFile, "surveyInfo.docx");

        // 查出数据
        LambdaQueryWrapper<BusSurveyInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BusSurveyInfo::getId, id);
        Map<String, Object> map = busSurveyInfoService.getMap(wrapper);

        // 映射为模板
        XWPFDocument document = WordExportUtil.exportWord07(templateFile.getPath(), map);
        String filename = "查勘报告.docx";

        // 导出
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "ISO8859-1"));
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        document.write(response.getOutputStream());
        document.close();
    }
}
